<template>
  <view class="login-page">
    <!-- 导航栏 -->
    <NavBar @back="goBack" />
    
    <!-- 登录内容 -->
    <view class="login-content">
      <view class="login-container">
        <view class="login-header">
          <text class="title">获取您的昵称、头像</text>
          <text class="subtitle">用于向其他用户展示</text>
        </view>

        <view class="avatar-section">
          <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" @error="onChooseAvatarError" :disabled="uploading">
            <image class="avatar" :src="avatarUrl || '/static/images/default-avatar.png'" mode="aspectFill" />
            <view class="camera-icon" v-if="!uploading">
              <image class="camera-img" src="/static/images/camera.png" mode="aspectFit" />
            </view>
            <view class="upload-overlay" v-if="uploading">
              <text class="upload-text">上传中...</text>
            </view>
          </button>
          <text class="avatar-tip">{{
            uploading ? '头像上传中...' : '点击更换头像'
          }}</text>
        </view>

        <view class="nickname-section">
          <input class="nickname-input" type="nickname" v-model="nickname" placeholder="请输入昵称"
            placeholder-class="placeholder" />
        </view>

        <button class="confirm-btn" @click="handleConfirm">确认</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { uploadFile } from '@/api/upload'
import NavBar from '@/components/NavBar.vue'

const userStore = useUserStore()

const avatarUrl = ref('')
const uploadedAvatarUrl = ref('')
const nickname = ref('')
const uploading = ref(false)

const onChooseAvatar = async (e: any) => {
  console.log('onChooseAvatar 事件触发:', e)
  
  try {
    uploading.value = true
    
    // chooseAvatar 返回的是本地临时文件路径，不需要下载
    const tempFilePath = e.detail.avatarUrl
    console.log('获取到的头像临时文件路径:', tempFilePath)
    
    if (!tempFilePath) {
      throw new Error('未获取到头像文件路径')
    }
    
    // 更新显示的头像
    avatarUrl.value = tempFilePath
    
    // 获取文件信息，确定正确的文件扩展名
    const fileInfo = await getFileInfo(tempFilePath)
    const timestamp = Date.now()
    
    // 根据文件类型确定扩展名
    let extension = 'jpg'
    if (fileInfo && fileInfo.type) {
      if (fileInfo.type.includes('png')) {
        extension = 'png'
      } else if (fileInfo.type.includes('jpeg') || fileInfo.type.includes('jpg')) {
        extension = 'jpg'
      } else if (fileInfo.type.includes('webp')) {
        extension = 'webp'
      } else if (fileInfo.type.includes('gif')) {
        extension = 'gif'
      }
    }
    
    // 生成带有正确扩展名的文件名
    const fileName = `avatar_${timestamp}.${extension}`
    
    console.log('头像上传信息:', {
      tempFilePath,
      fileInfo,
      extension,
      fileName
    })
    
    // 上传到服务器
    const result = await uploadFile({ 
      filePath: tempFilePath,
      name: fileName,
      type: extension
    })
    
    console.log('上传结果:', result)
    
    if (result.success && result.url) {
      uploadedAvatarUrl.value = result.url
      uni.showToast({
        title: '头像上传成功',
        icon: 'success'
      })
    } else {
      throw new Error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('处理头像失败:', error)
    uni.showToast({
      title: error instanceof Error ? error.message : '头像处理失败',
      icon: 'none'
    })
  } finally {
    uploading.value = false
  }
}

// 处理 chooseAvatar 错误
const onChooseAvatarError = (e: any) => {
  console.error('chooseAvatar 失败:', e)
  uploading.value = false
  
  uni.showModal({
    title: '提示',
    content: '头像选择功能不可用，是否使用备用方式选择头像？',
    success: (res) => {
      if (res.confirm) {
        chooseImageFallback()
      }
    }
  })
}

// 备用选择图片方式
const chooseImageFallback = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      if (tempFilePath) {
        // 直接使用本地文件路径
        await processLocalAvatar(tempFilePath)
      }
    },
    fail: (error) => {
      console.error('选择图片失败:', error)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 处理本地头像文件
const processLocalAvatar = async (tempFilePath: string) => {
  try {
    uploading.value = true
    
    // 更新显示的头像
    avatarUrl.value = tempFilePath
    
    // 获取文件信息，确定正确的文件扩展名
    const fileInfo = await getFileInfo(tempFilePath)
    const timestamp = Date.now()
    
    // 根据文件类型确定扩展名
    let extension = 'jpg'
    if (fileInfo && fileInfo.type) {
      if (fileInfo.type.includes('png')) {
        extension = 'png'
      } else if (fileInfo.type.includes('jpeg') || fileInfo.type.includes('jpg')) {
        extension = 'jpg'
      } else if (fileInfo.type.includes('webp')) {
        extension = 'webp'
      } else if (fileInfo.type.includes('gif')) {
        extension = 'gif'
      }
    }
    
    // 生成带有正确扩展名的文件名
    const fileName = `avatar_${timestamp}.${extension}`
    
    console.log('头像上传信息:', {
      tempFilePath,
      fileInfo,
      extension,
      fileName
    })
    
    // 上传到服务器
    const result = await uploadFile({ 
      filePath: tempFilePath,
      name: fileName,
      type: extension
    })
    
    console.log('上传结果:', result)
    
    if (result.success && result.url) {
      uploadedAvatarUrl.value = result.url
      uni.showToast({
        title: '头像上传成功',
        icon: 'success'
      })
    } else {
      throw new Error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('处理本地头像失败:', error)
    uni.showToast({
      title: error instanceof Error ? error.message : '头像处理失败',
      icon: 'none'
    })
  } finally {
    uploading.value = false
  }
}

const handleConfirm = async () => {
  if (!nickname.value.trim()) {
    return uni.showToast({ title: '请输入昵称', icon: 'none' })
  }

  try {
    const { code } = await uni.login({ provider: 'weixin' })
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const redirectUri = `/${currentPage.route}`

    await userStore.loginWithWechat({
      code,
      redirectUri,
      avatarUrl: uploadedAvatarUrl.value || avatarUrl.value,
      nickname: nickname.value
    })

    uni.showToast({ title: '登录成功', icon: 'success' })
    
    // 发送登录成功事件，通知其他页面刷新
    uni.$emit('loginSuccess')
    
    // 登录成功后返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (err) {
    console.error('登录失败:', err)
    uni.showToast({ title: '登录失败，请重试', icon: 'none' })
  }
}

const goBack = () => {
  uni.navigateBack()
}

// 获取文件信息
const getFileInfo = (filePath: string): Promise<any> => {
  return new Promise((resolve, reject) => {
    uni.getFileInfo({
      filePath: filePath,
      success: (res) => {
        resolve(res)
      },
      fail: (error) => {
        console.warn('获取文件信息失败:', error)
        resolve(null) // 获取失败时返回null，使用默认扩展名
      }
    })
  })
}
</script>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.login-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 32rpx;
  box-sizing: border-box;
  width: 100%;
}

.login-container {
  width: 100%;
  max-width: 600rpx;
  border-radius: 24rpx;
  padding: 60rpx 40rpx;
  box-sizing: border-box;
  margin: 0 auto;
}

.login-header {
  text-align: center;
  margin-bottom: 60rpx;

  .title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    display: block;
    margin-bottom: 12rpx;
  }

  .subtitle {
    font-size: 28rpx;
    color: #999;
  }
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;

  .avatar-wrapper {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 24rpx;
    padding: 0;
    border: none;
    background: none;

    &::after {
      border: none;
    }

    .avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background: #f5f5f5;
    }

    .camera-icon {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 60rpx;
      height: 60rpx;
      background: #07c160;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      .camera-img {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .avatar-tip {
    font-size: 26rpx;
    color: #999;
  }

  .upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .upload-text {
    color: #fff;
    font-size: 24rpx;
    font-weight: 500;
  }
}

.nickname-section {
  margin-bottom: 60rpx;

  .nickname-input {
    width: 100%;
    height: 100rpx;
    background: #f5f5f5;
    border-radius: 16rpx;
    padding: 0 32rpx;
    font-size: 32rpx;
    color: #333;
    box-sizing: border-box;
  }

  .placeholder {
    color: #999;
  }
}

.confirm-btn {
  width: 100%;
  height: 100rpx;
  background: #07c160;
  border-radius: 50rpx;
  color: #fff;
  font-size: 36rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  box-sizing: border-box;

  &::after {
    border: none;
  }

  &:active {
    opacity: 0.9;
  }
}
</style>
